package org.ruanjj.multithread;

import java.util.concurrent.locks.ReentrantLock;

public class ReentrantlockTest {
    public static void main(String[] args) {
        SaleTicket s1 = new SaleTicket("售票窗口1");
        SaleTicket s2 = new SaleTicket("售票窗口2");
        SaleTicket s3 = new SaleTicket("售票窗口3");
        SaleTicket s4 = new SaleTicket("售票窗口4");

        s1.start();
        s2.start();
        s3.start();
        s4.start();
    }
}

class SaleTicket extends Thread{
    private static int tickets = 100;
    private static final ReentrantLock lock = new ReentrantLock();
    private String name;

    public SaleTicket(String name){
        super(name);
    }
    @Override
    public void run(){
        while(true){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            try{
                lock.lock();
                if(tickets > 0){
                    System.out.println(Thread.currentThread().getName()+"售票"+tickets);
                    tickets--;
                }else{
                    break;
                }
            }finally {
                lock.unlock();
            }
        }
    }
}
